<template>
  <div>
    <div class="search">
      <input class="search-input" v-model="keyword" type="text" placeholder='输入城市名称或拼音'>
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
          v-for="item of list"
          :key="item.id"
          class="search-item border-bottom"
          @click="handleClickCity(item.name)"
        >{{item.name}}</li>
        <li class="search-item border-bottom" v-show="!list.length">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default{
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: []
    }
  },
  methods: {
    handleClickCity (city) {
      this.editCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['editCity'])
  },
  watch: {
    keyword () {
      console.log(!this.keyword)
      // null、undefined、0、“ ”都会被转为flase。
      if (!this.keyword) {
        this.list = []
        // return空直接退出函数
        return
      }
      setTimeout(() => {
        const result = []
        for (let i in this.cities) {
        // console.log(this.cities[i])
        // 箭头函数中的this指向是固定不变的，一直指向的是定义函数的环境。
          this.cities[i].forEach((item) => {
            if (item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
              // console.log(item)
              result.push(item)
            }
          })
        }
        this.list = result
        // console.log(this.list)
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .search
    padding 0 .1rem 0 .1rem
    height .72rem
    background $bgColor
    .search-input
      height .62rem
      line-height .62rem
      border-radius .08rem
      width 100%
      text-align center
      color #666
      padding 0 .23rem
      box-sizing border-box
  .search-content
    overflow hidden
    z-index 1
    position absolute
    top 1.57rem
    left 0
    right 0
    bottom 0
    background #fff
    .search-item
      padding-left .23rem
      line-height .63rem
      background #fff
</style>
